package com.iwork.platform.service;

import com.iwork.platform.util.CaptchaUtil;
import com.iwork.platform.util.CookiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


/**
 * 如梦验证码
 *
 * @author L.cm
 */
@Slf4j
@Component
public class CaptchaService implements InitializingBean {
    private static final String DEFAULT_COOKIE_NAME = "dream-captcha";
    private final static int DEFAULT_MAX_AGE = -1; // cookie超时默认为session会话状态

    private String cookieName;

    public CaptchaService() {
        this.cookieName = DEFAULT_COOKIE_NAME;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(cookieName, "cookieName must not be empty!");
    }

    /**
     * 生成验证码
     */
    public void generate(HttpServletRequest request, HttpServletResponse response) {
        // 先检查cookie的uuid是否存在
        String cookieValue = CookiesUtils.getCookieValue(request, cookieName);
        boolean hasCookie = true;
        if (StringUtils.isEmpty(cookieValue)) {
            hasCookie = false;
            cookieValue = UUID.randomUUID().toString();
        }
        String captchaCode = CaptchaUtil.generateCode().toUpperCase();// 转成大写重要
        // 不存在cookie时设置cookie
        if (!hasCookie) {
            CookiesUtils.setCookie(response, cookieName, cookieValue, DEFAULT_MAX_AGE);
        }
        // 生成验证码
        request.getSession().setAttribute(cookieValue, captchaCode);
        CaptchaUtil.generate(response, captchaCode);
    }

    /**
     * 仅能验证一次，验证后立即删除
     *
     * @param request          HttpServletRequest
     * @param response         HttpServletResponse
     * @param userInputCaptcha 用户输入的验证码
     * @return 验证通过返回 true, 否则返回 false
     */
    public boolean validate(HttpServletRequest request, HttpServletResponse response, String userInputCaptcha) {
        if (log.isDebugEnabled()) {
            log.debug("validate captcha userInputCaptcha is {}", userInputCaptcha);
        }
        String cookieValue = CookiesUtils.getCookieValue(request, cookieName);
        if (StringUtils.isEmpty(cookieValue)) {
            return false;
        }
        HttpSession session = request.getSession();
        String captchaCode = (String) session.getAttribute(cookieValue);
        if (StringUtils.isEmpty(captchaCode)) {
            return false;
        }
        // 转成大写重要
        userInputCaptcha = userInputCaptcha.toUpperCase();
        boolean result = userInputCaptcha.equals(captchaCode);
        if (result) {
            session.removeAttribute(cookieValue);
            CookiesUtils.removeCookie(response, cookieName);
        }
        return result;
    }
}
